import axios from 'axios';
import baseUrl from './api';
import qs from 'qs';
import Vue from 'vue';
import { Toast } from 'cube-ui';
import moment from 'moment';

Vue.use(Toast);

const HTTP_OUT_TIME = 10000;

//设置请求的根路径
axios.defaults.baseURL = baseUrl;
//设置超时时间
axios.defaults.timeout = HTTP_OUT_TIME;
//格式化请求参数
axios.defaults.transformRequest = function(param) {
  // param = JSON.stringify(param);
  param = qs.stringify(param);
  return param;
};

/**
 * axios请求拦截器
 */
axios.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    showLoading();
    //判断是否存在ticket，如果存在的话，则每个http header都加上ticket
    // if (cookie.get('token')) {
    //   //用户每次操作，都将cookie设置成2小时
    //   cookie.set('token', cookie.get('token'), 1 / 12);
    //   cookie.set('name', cookie.get('name'), 1 / 12);
    //   config.headers.token = cookie.get('token');
    //   config.headers.name = cookie.get('name');
    // }

    return config;
  },
  error => {
    return Promise.reject(error.response);
  }
);

/**
 * axios路由响应拦截
 * http response 拦截器
 */
axios.interceptors.response.use(
  response => {
    console.log(response);
    tryHideLoading();

    if (response.data.errorCode == '404') {
      console.log('response.data.resultCode是404');
      //其他处理逻辑
      return;
    } else {
      if (response.status === 200) {
        return response;
      }
    }
  },
  error => {
    tryHideLoading();
    return Promise.reject(error.response); // 返回接口返回的错误信息
  }
);

/**
 * 记录并发请求数，并处理加载动画显示与隐藏
 */
let needLoadingRequestCount = 0;
let loading;
let startTime;
let endTime;
const LOADING_TIME = 500;
/**
 * 展示加载动画
 *
 * @author LiangJ
 */
function showLoading() {
  if (needLoadingRequestCount === 0) {
    startTime = moment().valueOf();
    loading = Toast.$create({
      time: HTTP_OUT_TIME,
      mask: true
    });
    loading.show();
  }
  needLoadingRequestCount++;
}
/**
 * 请求结束时，隐藏加载动画
 *
 * @author LiangJ
 * @returns
 */
function tryHideLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endTime = moment().valueOf();
    const httpTime = endTime - startTime;
    if (httpTime < LOADING_TIME) {
      setTimeout(() => {
        loading && loading.hide();
      }, LOADING_TIME - httpTime);
    } else {
      loading && loading.hide();
    }
  }
}

export default axios;
